//
//  UITabBar+LLBadge.m
//  live.ly
//
//  Created by JunhuaRao on 16/10/21.
//  Copyright © 2016年 musical.ly. All rights reserved.
//

#import "UITabBar+LLBadge.h"
#import "MUSPaddingLabel.h"

#define TabbarItemNums 5.0


@interface UITabBar ()

@end


@implementation UITabBar (LLBadge)

- (void)showBadgeOnItemIndex:(int)index number:(NSNumber *)badgeNumber
{
    [self removeBadgeOnItemIndex:index];

    if (badgeNumber.integerValue == 0) return;

    MUSPaddingLabel *badgeLabel = [[MUSPaddingLabel alloc] init];
    badgeLabel.cornerRadius = 9;
    [badgeLabel setTextAlignment:NSTextAlignmentCenter];
    [badgeLabel setTextColor:[UIColor whiteColor]];
    [badgeLabel setBackgroundColor:ColorFromHEX(@"FF0F50")];
    [badgeLabel setFont:[UIFont ll_appFontMediumWithSize:12]];
    badgeLabel.tag = index;
    badgeLabel.text = [NSString stringWithFormat:@"%@", badgeNumber];
    badgeLabel.adjustsFontSizeToFitWidth = YES;

    CGFloat width = [badgeLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont ll_appFontMediumWithSize:12]}].width;
    if (width > 14.2) {
        width = width + 12;
        if (width > 29) width = 31;
    } else if (width <= 13) {
        width = 18;
    }
    CGRect tabFrame = self.frame;
    float percentX = (index + 0.6) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeLabel.frame = CGRectMake(x - 2, y + 2, width, 18);
    [self addSubview:badgeLabel];
}

- (void)removeBadgeOnItemIndex:(int)index
{
    for (UIView *subView in self.subviews) {
        if (subView.tag == index) {
            [subView removeFromSuperview];
        }
    }
}

@end
